import { getComponentRootDom } from "../tools";
import styles from "./showMessage.module.less";

import Icon from "@/components/Icon";

/**
 * 消息弹出层
 * @param {object} options 配置项
 * @param {string} options.content 消息内容
 * @param {string} options.type 消息类型
 * @param {number} options.duration 消息显示时间
 * @param {HTMLElement} options.container 容器 消息显示在页面正中,不传显示在页面正中
 * @param {function} callback 回调函数
 * */

export default function showMessage(
  { content, type = "info", duration = 2000, container },
  callback
) {
  // 创建消息元素
  const div = document.createElement("div");
  const typeClassName = `message-${type}`;
  div.className = `${styles.message} ${styles[typeClassName]}`;
  const iconDom = getComponentRootDom(Icon, { type });
  div.innerHTML = `<span class="${styles.icon}">${iconDom.outerHTML}</span><div>${content}</div>`;
  // 加入到容器中
  if (container) {
    if (getComputedStyle(container).position === "static") {
      container.style.position = "relative";
    }
  } else {
    container = document.body;
  }
  container.appendChild(div);

  let timer = null;

  // 显示消息
  timer = setTimeout(() => {
    div.style.opacity = 1;
    div.style.transform = "translate(-50%, -50%) translateY(0px)";
  }, 100);

  // 隐藏消息
  timer = setTimeout(() => {
    div.style.opacity = 0;
    div.style.transform = "translate(-50%, -50%) translateY(15px)";
    div.addEventListener("transitionend", () => {
      div.remove();
      clearTimeout(timer);
      callback && callback();
    });
  }, duration);
}
